package com.xiang.utils.aggs;


import com.xiang.config.EsConfig;
import com.xiang.utils.CreateDoc;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.range.ParsedRange;
import org.elasticsearch.search.aggregations.bucket.range.Range;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.List;

/**
 * 范围查询
 *
 * @author xiangtianlei@gogpay.cn
 * @date 2023-01-30
 */
public class RangeQuery {
    RestHighLevelClient client = EsConfig.getClient();
    Logger logger = LoggerFactory.getLogger(CreateDoc.class);

    /**
     * 范围查询
     */
    @Test
    public void rangeQuery() throws IOException {
        // 创建request
        SearchRequest request = new SearchRequest(EsConfig.INDEX_NAME);
        // 封装DSL
        SearchSourceBuilder builder = new SearchSourceBuilder();
        builder.aggregation(AggregationBuilders.range("age").field("age")
                .addUnboundedTo(20)
                .addRange(20, 50)
                .addUnboundedFrom(50));
        request.source(builder);
        // 执行查询
        SearchResponse res = client.search(request, RequestOptions.DEFAULT);
        // 获取返回的结果
        List<? extends Range.Bucket> buckets = ((ParsedRange) res.getAggregations().get("age")).getBuckets();
        for (Range.Bucket bucket : buckets) {
            String key = bucket.getKeyAsString();
            Object from = bucket.getFrom();
            Object to = bucket.getTo();
            long docCount = bucket.getDocCount();
            logger.info("查询key：{}，从{}，开始，从{}结束，数量：{}", key, from, to, docCount);
        }

    }

}
